Swap Nodes In Pairs

题目描述(难度中等)

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

1
Given 1->2->3->4, you should return the list as 2->1->4->3.

方法一:遍历一遍链表

链表改变顺序的题目,通用的方法论是先找出一次需要改变指向的节点数量。交换相邻节点需要改变current(相邻节点前节点的前节点),first(相邻节点前节点),second(相邻节点后节点)。current在链表头部自定义一个初始值为0的节点。

cmd-markdown-logo

cmd-markdown-logo

上图中展示了链表指向的过程,三个节点都需要进行重定向,一次循环后的结果:

cmd-markdown-logo

第二次循环继续将current往后平移两个单位,继续执行循环赋值:

cmd-markdown-logo

得到循环赋值结果:

cmd-markdown-logo

方法一代码

分析了上图之后,代码实现较为简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ListNode swapPairsMoreClear(ListNode head){
ListNode current = new ListNode(0);
current.next = head;
ListNode newHead = current;
while (current.next !=null && current.next.next!=null){
ListNode first = current.next;
ListNode second = current.next.next;

current.next = second;
first.next= second.next;
second.next=first;

current = first;
}
return newHead.next;
}